package com.zhz.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.zhz.pojo.User;
import com.zhz.service.UserService;
import com.zhz.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 周恒哲
 * @since 2020-04-14
 */
@Controller
@RequestMapping("/user")
@Api(tags = {"用户控制类"})
public class UserController {

    @Autowired
    private UserService userService;

    //完成
    @GetMapping("/findById/{id}")
    @ApiOperation("根据ID查询用户信息")
    public String findById(@ApiParam("用户ID") @PathVariable("id") Long id, Model model) {

        try {
            User user = this.userService.getById(id);
            model.addAttribute("user",user);
            return "user/update";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //完成
    @GetMapping("/findAll")
    @ApiOperation("查询所有用户信息")
    public String findAll(Model model) {

        try {
            List<User> list = this.userService.list(null);
            model.addAttribute("list",list);
            return "user/list";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @PostMapping("/insertUser")
    @ApiOperation("添加用户(注册)")
    public String insertUser(@ApiParam("用户对象") User user) {

        try {
            boolean save = this.userService.save(user);
            System.out.println(save);
            return "redirect:/user/findAll";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @PostMapping("/updateUser")
    @ApiOperation("修改用户")
    public Result updateUser(@ApiParam("用户对象") User user) {
        try {
            user.setVersion(user.getVersion());
            boolean update = this.userService.updateById(user);
            System.out.println(update);
            return Result.ok(update);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.build(500, "error");
    }

    //完成
    @GetMapping("/deleteUserById/{id}")
    @ApiOperation("根据单个ID删除用户")
    public String deleteUserById(@ApiParam("用户ID") @PathVariable("id") Long id) {

        try {
            boolean remove = this.userService.removeById(id);
            return "redirect:/user/findAll";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("/deleteUserByIds")
    @ApiOperation("根据多个ID删除用户")
    public Result deleteUserByIds(@ApiParam("用户ID") @RequestParam Long[] ids) {

        try {
            boolean remove = this.userService.removeByIds(Arrays.asList(ids));
            System.out.println(remove);
            return Result.ok(remove);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.build(500, "error");
    }
    @GetMapping("/selUserByName")
    @ApiOperation("根据用户名字查询用户信息（模糊查询）")
    public String selUserByName(@ApiParam("用户名字") @RequestParam String username,Model model) {

        try {
            QueryWrapper<User> wrapper=new QueryWrapper<>();
            wrapper.like("username",username);
            List<User> list = this.userService.list(wrapper);
            model.addAttribute("username",username);
            model.addAttribute("list",list);
            return "user/list";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @GetMapping("/logout")
    @ApiOperation("注销")
    public String logout(HttpSession session) {

        session.invalidate();
        return "login";
    }
    //完成
    @PostMapping("/login")
    @ApiOperation("登录")
    public String login(@ApiParam("用户账号") @RequestParam("username") String username, @ApiParam("用户密码") @RequestParam("password") String password, HttpSession session, Model model) {

        try {
            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
                queryWrapper.eq("username", username).eq("password",password);
                User user = this.userService.getOne(queryWrapper);
                if (user!=null){
                    if (user.getRoleName().equals("ROLE_ADMIN")){
                        session.setAttribute("user",user);
                        return "index";
                    }else {
                        session.setAttribute("user",user);
                        return "fontIndex";
                    }

                }else {
                    model.addAttribute("msg","用户名或者密码不正确，请重新输入");
                    return "login";
                }

            } else {
                model.addAttribute("msg","用户名或者密码不正确，请重新输入");
                return "login";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        model.addAttribute("msg","用户名或者密码不正确，请重新输入");
        return "login";
    }
    @PostMapping("/registerUser")
    @ApiOperation("添加用户(注册)")
    public String registerUser(@ApiParam("用户对象") User user) {

        try {
            user.setRoleName("ROLE_USER");
            boolean save = this.userService.save(user);
            System.out.println(save);
            return "login";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

